var util = require('../../utils/util.js')
var md5 = require('../../utils/md5.js')

// var url = "https://talk.leautolink.com";
 var url = "https://talk.airmmi.com";
// var url = "http://localhost:8080";

const app = getApp()

const recorderManager = wx.getRecorderManager()

const backgroundAudioManager = wx.getBackgroundAudioManager();

const innerAudioContext = wx.createInnerAudioContext();

const voiceOptions = {
  duration: 10000,
  sampleRate: 16000,
  numberOfChannels: 1,
  encodeBitRate: 96000,
  format: 'mp3',
  frameSize: 50
}
var boot = {
  role: 'robot',
  flex_direction: 'row',
  message: '您可以说：\n\n ' +
  '我要听李白的诗\n' +
  '我要听评书\n' +
  '给我讲个笑话\n' +
  // '我要玩成语接龙\n' +
  '明天北京的天气\n' +
  '今天北京尾号限行\n'
}

var dialog = []

Page({
  onLoad: function () {
    // console.info("onLoad");
    this.getContent();

    var _this = this;
    innerAudioContext.obeyMuteSwitch = false;

    innerAudioContext.onStop((res) => {
      // console.info('播放停止了')
      // console.info(res)
      _this.deleteAudio();
    });
    innerAudioContext.onEnded((res) => {
      // console.info('播放结束了')
      // console.info(res);
      _this.deleteAudio();
    })

    recorderManager.onStop((res) => {
      // console.log('recorder stop', res)
      const { tempFilePath } = res

      // innerAudioContext.src = tempFilePath;
      // innerAudioContext.play();
      _this.uploadVoice(tempFilePath);

    });
  },

  onShow:function () {
    // console.info("onShow");
    wx.hideNavigationBarLoading()
  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '说出你想听的，我都会满足你！',
      path: 'pages/index/index',
      imageUrl: url + '/images/share.jpg',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  getContent: function () {
    var _this = this;
      wx.request({
        url: url + '/api/v2/content/',
        method: 'GET',
        success: function (res) {
          var data = res.data;
          var resultData = data.data;
          boot = {
            role: 'robot',
            flex_direction: 'row',
            message: resultData.content
          }
          dialog.push(boot);
          _this.setData({
            dialog: dialog
          });
        },
        fail: function (res) {
          dialog.push(boot);
          _this.setData({
            dialog: dialog
          });
        }
      })

  },

  deleteAudio: function () {
    if (this.currentPlayId) {
      wx.request({
        url: url + '/api/v2/audio/' + this.currentPlayId,
        // url: 'http://localhost:8082/api/v2/audio/retalk1.mp3',
        // header: header,
        method: 'DELETE'
      })
      this.currentPlayId = '';
    }
  },

  data: {
    image: '/images/voice.png',
    dialog: dialog
  },

  addText: function (context) {
    var itemId = Math.random() + "";
    itemId = "ID" + itemId.replace(/[^\d]/g, '');

    context.itemId = itemId;

    var lastItem = dialog[dialog.length - 1];
    if (lastItem.role == 'user_speak' || lastItem.role == 'robot_speak') {
      dialog[dialog.length - 1] = context;
    } else {
      dialog.push(context)
    }

    this.setData({
      dialog: dialog
    });

    this.pageScrollToBottom(itemId)
  },

  openVoice: function (e) {

    backgroundAudioManager.pause();
    innerAudioContext.stop();

    var _this = this;
    // console.log("打开录音")

    // innerAudioContext.src = '/audios/ding.wav'
    // innerAudioContext.play();

    recorderManager.start(voiceOptions);

    this.setData({
      image: '/images/voiceing.png'
    });

    _this.showToast();

    this.addText({
      role: 'user_speak',
      flex_direction: 'row-reverse'
    });
  },

  closeVoice: function (e) {
    var _this = this;
    // console.log("关闭录音")

    recorderManager.stop(voiceOptions)
    this.hideToast();

    setTimeout(function () {
      _this.setData({
        image: '/images/voice.png'
      });
    }, 100);
  },

  uploadVoice: function (tempFilePath) {
    var _this = this;

    var header = this.createHeader();

    var str = "noncestr=" + header.noncestr + "&platform=" + header.platform + "&timestamp=" + header.timestamp + "&uid=" + header.uid + "&appkey=" + app.appkey;

    var sign = md5.hex_md5(str);
    header['sign'] = sign;

    wx.uploadFile({
      url: url + '/api/v2/content',
      filePath: tempFilePath,
      name: 'file',
      header: header,
      formData: {
        test: 'test'
      },
      success: function (res) {

        // console.info(res.data);
        var data = JSON.parse(res.data);
        var resultData = data.data;

        if (resultData.complete == "-2") {
          _this.addText({
            role: 'robot',
            flex_direction: 'row',
            message: resultData.content
          });

          // innerAudioContext.autoplay = true
          innerAudioContext.src = url + '/talks/retalk.mp3'
          innerAudioContext.play();

          return;

        } else {
          _this.addText({
            role: 'user',
            flex_direction: 'row-reverse',
            message: resultData.content
          });
        }

        _this.addText({
          role: 'robot_speak',
          flex_direction: 'row'
        });

        _this.voiceAnalysis(resultData.content);
      },
      fail: function (res) {
        // console.info(res);
        _this.addText({
          role: 'robot',
          flex_direction: 'row',
          message: '网络异常，请稍后再试！'
        });
      }
    })
  },

  voiceAnalysis: function (content) {

    var header = this.createHeader();

    var str = "content=" + content + "&noncestr=" + header.noncestr + "&platform=" + header.platform + "&timestamp=" + header.timestamp + "&uid=" + header.uid + "&appkey=" + app.appkey;

    var sign = md5.hex_md5(str);

    header['content-type'] = 'application/x-www-form-urlencoded'
    header['sign'] = sign;

    var _this = this;
    wx.request({
      url: url + '/api/v2/analysis',
      data: {
        content: content,
        sessionId: this.sessionId ? this.sessionId : ''
      },
      header: header,
      method: 'POST',
      success: function (res) {
        if (res.statusCode != 200 || res.data.code != "10000") {
          _this.addText({
            role: 'robot',
            flex_direction: 'row',
            message: '网络异常，请稍后再试！'
          });
          return;
        }

        // console.log(res.data)

        var resultData = res.data.data;
        _this.sessionId = resultData.sessionId;

        _this.addText({
          role: 'robot',
          flex_direction: 'row',
          message: resultData.content
        });

        if (resultData.complete != "1") {
          innerAudioContext.src = url + '/talks/' + resultData.object;
          innerAudioContext.play();

          _this.currentPlayId = resultData.object;
          return;
        }

        var resultObject = JSON.parse(resultData.object);

        var resultObjectData = resultObject.data;

        var audios = resultObjectData.audios;
        var audio = audios[0];

        wx.setStorage({
          key: "audios",
          data: resultObjectData
        })

        wx.setStorageSync('currentPlay', {
          audio: audio,
          index: 0
        });

        wx.navigateTo({
          url: '/pages/audio/audio'
        })
      },
      fail: function (res) {
        // console.info(res);
        _this.addText({
          role: 'robot',
          flex_direction: 'row',
          message: '网络异常，请稍后再试！'
        });
      }
    })
  },

  pageScrollToBottom: function (dialog_item_id) {
    this.setData({
      dialog_item_id: dialog_item_id
    })
  },

  showToast: function () {
    wx.showToast({
      title: "请说话",
      icon: "loading",
      // image: "/images/volume.gif",
      duration: 10000
    })
  },

  hideToast: function () {
    wx.hideToast()
  },

  createHeader: function () {
    return {
      'timestamp': Date.now(),
      'noncestr': util.guid(),
      'uid': app.userId,
      'platform': app.platform
    }
  },

  handletouchmove: function (event) {

    var touch = event.changedTouches[0];
    // console.log(touch)

    this.setData({
      left: touch.pageX,
      top: touch.pageY,
    });
  },

  playImageClick: function () {
    wx.navigateTo({
      url: '/pages/audio/audio?reOpen=true'
    })
  },

  showPlayImage: function (playImage) {
    this.setData({
      playImage: playImage
    });
  },

  currentPlayId: ''
})